<?php
declare(strict_types=1);
/**
 * 库存扣减服务
 */
namespace Service\CommodityService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\CommodityModel\Stockinfo;
use App\Model\CommodityModel\StockInfoUserLog;
use Service\AppService\IdService;
class StockMysqlService extends BaseService
{
    /**
     * 扣减库存服务
     * @param string $key
     * @param int $number
     */
    public function decrease(string $key,int $number)
    {
        try 
        {
            
            $result = Stockinfo::instance()->where('ID',$key)->decrement("Number",$number);
            StockInfoUserLog::instance()->insert([
                'ID'    => IdService::instance()->getLogID(),
                'BuID'  => 0,
                'StockID'   => $key,
                'StockType' => 1,
                'StockNumber'   => $number,
                'CreateTime'    => date("Y-m-d H:i:s")
            ]);
        } 
        catch ( \Throwable $th ) 
        {
            return Normal::returnCode(Normal::FAIL,"扣减失败-{$th->getMessage()},{$th->getFile()},{$th->getLine()}");
        }
    }
    
    /**
     * 新增库存服务
     * @param string $key
     * @param int $number
     */
    public function increase(string $key,int $number)
    {
        try
        {
            $redis = redis();
            $redis->multi();
            $redis->incr($key,$number);
            $result = $redis->exec();
            $current_element = current($result);
            return Normal::returnCode(Normal::SUC,"新增成功-{$current_element}");
        }
        catch ( \Throwable $th )
        {
            return Normal::returnCode(Normal::FAIL,"新增失败-{$th->getMessage()},{$th->getFile()},{$th->getLine()}");
        }
    }
}